package com.lwl.blog.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.lwl.blog.core.utils.UUIDUtils;
import com.lwl.blog.system.constants.RedisKey;
import com.lwl.blog.system.dto.UserToken;
import com.lwl.blog.system.entity.SystemUserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * token令牌业务层
 * </p>
 *
 * @author lwl
 * @since 22-12-26
 */

@Service
public class TokenService {

    //redis
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 默认超时时间30min
    private Long defaultTimeOut = 30 * 60 * 1000L;

    //创建token方法
    public UserToken createToken(SystemUserEntity systemUserEntity) {

        //1.将用户登录信息封装到usertoken对象中
        UserToken userToken = new UserToken();
        Date createTime = new Date();
        // 登录时间
        userToken.setCreateTime(createTime);
        // 超时时间=登录时间+30min默认超时时间
        long timeout = createTime.getTime() + defaultTimeOut;
        // 把Long类型转成Date类型
        userToken.setTimeout(new Date(timeout));

        //将登录信息封装到usertoken中
        userToken.setUserId(systemUserEntity.getId());
        userToken.setUsername(systemUserEntity.getUsername());
        // 登录用户的令牌，返回给前端
        userToken.setToken(UUIDUtils.getId());

        // 以用户的token(令牌）作为key的唯一标识
        String token = userToken.getToken();
        String key = String.format(RedisKey.USER_LOGIN_KEY, token);

        //将用户登录信息保存到redis中，过期时间30min
        stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(userToken), 30, TimeUnit.MINUTES);

        return userToken;
    }

    //获得token的方法
    public UserToken getToken(String token) {

        String key = String.format(RedisKey.USER_LOGIN_KEY, token);
        String json = stringRedisTemplate.opsForValue().get(key);

        if (ObjectUtils.isEmpty(json)) {
            return null;
        }
        return JSON.parseObject(json, UserToken.class);
    }
}
